package com.xiia.admin.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.xiia.common.servlet.FrameworkServlet;
import com.xiia.servcie.imp.ResourceService;
import com.xiia.servcie.imp.ResourceSortService;
import com.xiia.service.inter.IResource;
import com.xiia.service.inter.IResourceSort;
import com.xiia.util.CheckConstant;
import com.xiia.util.Pager;
import com.xiia.util.ParamUtil;
import com.xiia.util.StringUtil;
import com.xiia.vo.Resource;
import com.xiia.vo.ResourceSort;
import com.xiia.vo.User;

/**
 * 2014-11-4
 * @author 王书恒
 *资源后台Servlet
 */
@WebServlet("/resource.do")
public class ResourceServlet extends FrameworkServlet{
	private static final long serialVersionUID = 1L;
	private static IResource iResource;
	private static IResourceSort iResourceSort;
	private static Pager page;
	
	public ResourceServlet(){
		iResource = new ResourceService();
		iResourceSort = new ResourceSortService();
		page = new Pager();
	}
	
	/**
	 * 跳转到添加资源的界面
	 * @param request
	 * @param response
	 * @return 
	 * @throws Exception 
	 */
	public String toAddResourceUI(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		//找到所有的资源分类
		List<ResourceSort> rsList = iResourceSort.getAllResourceSort();
		request.setAttribute("rsList", rsList);
		return "bclient/resource/addResource.jsp";
	}
	/**
	 * 创建新的资源
	 * @param request
	 * @param response
	 * @return 
	 * @throws Exception 
	 */
	public String addResource(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		Resource r = new Resource();
		User loginUser = (User) request.getSession().getAttribute(ParamUtil.LOGIN_USER);
		resString = "";
		//得到一个上传的对象upload
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items;
		FileItem upItem = null;
		items = upload.parseRequest(request);
		for(FileItem item : items){
			if(!item.isFormField()){
				upItem = item;
				//判断文件大小
				if(item.getSize() > ParamUtil.UPLOAD_RESOURCE_FILE_SIZE * 1024 * 1024){
					resString = "您的资源文件超出"+ParamUtil.UPLOAD_RESOURCE_FILE_SIZE+"M\n";
				}
				
				boolean isAcceptExt = isAcceptExtFile(StringUtil.getFileExtention(item.getName()));
				if(!isAcceptExt){
					resString += "暂时支持"+ParamUtil.ACCEPT_UPLOAD_RESOURCE_FILE_TYPE+"的文件类型";
				}
				
			}else{
				if(item.getFieldName().equals("resScore")){
					r.setResScore(Integer.parseInt(item.getString().trim()));
				}else if(item.getFieldName().equals("sortId")){
					r.setSortId(Integer.parseInt(item.getString().trim()));
				}
			}
		}
		
		if(resString.length() > 0){
			request.setAttribute("resString", resString);
			return toAddResourceUI(request,response);
		}
		
		if(upItem != null){
			//上传文件
			r.setFileName(upItem.getName());
			r.setFileSize(upItem.getSize());
			String root = request.getSession().getServletContext().getRealPath("/");//D:\Tomcat 7.0\wtpwebapps\Friend\
			//上传到upload/userId/resource/2014-7-25/file.jpg
			String currentDate = StringUtil.getCurrentDateInDir();
			String extention = StringUtil.getFileExtention(upItem.getName());
			String uploadDir = "upload/"+ loginUser.getUserId() + "/resource/" + currentDate + "/";
			String relativePath = uploadDir + UUID.randomUUID()+ extention;
			uploadFileByItem(upItem, relativePath, uploadDir, root);
			//将resource写入到数据库中
			r.setAddTime(new Date());
			r.setStatus(CheckConstant.STATUS_WRITE_DONE);
			r.setUser(loginUser);
			r.setFilePath(relativePath);
			if(iResource.addResource(r)){
				resString = "上传资源成功";
			}else{
				resString = "上传资源失败";
			}
		}
		request.setAttribute("resString", resString);
		return toAddResourceUI(request,response);
	}
	/**
	 * 查询所有资源分类
	 * @param request
	 * @param response
	 * @return
	 */
	public String list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int currentPage=1;
		if(request.getParameter("currentPage")!=null){
			currentPage=Integer.parseInt(request.getParameter("currentPage").toString());
		}
		//得到Resource的总行数
		int totalCount=iResource.countResource();
		page.paging(currentPage, ParamUtil.RESOURCE_PAGE_SIZE, totalCount);
		page =iResource.findResourcePage(page,"resId");
		request.setAttribute("page",page);
		
		return "bclient/resource/resourceList.jsp";
	}
	
	
	
	/**
	 * 删除资源
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */	
	
	public String deleteResource(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,Exception {
		Resource resource = doForm(request);
		if(iResource.deleteResource(resource)){
			resString = "删除成功";
		}else{
			resString = "删除失败";
		}
		request.setAttribute("resString", resString);
		return list(request, response);
	}
	
	/**
	 * 跳转到修改页面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	public String toUpdateResourceUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,Exception {
		Resource resource = doForm(request);
		resource=iResource.getResourceById(resource.getResourceId());
		List<ResourceSort> rsList = iResourceSort.getAllResourceSort();
		request.setAttribute("rsList", rsList);
		request.setAttribute("resource", resource);
		return "bclient/resource/updateResource.jsp";
	}
	/**
	 * 修改资源
	 * @param request
	 * @param response
	 * @return 
	 * @throws Exception 
	 */
	public String updateResource(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,Exception {
		Resource resource = doForm(request);
		if(iResource.updateResource(resource)){
			resString = "修改成功";
		}else{
			resString = "修改失败";
		}
		request.setAttribute("resString", resString);
		return list(request, response);
	}
	/**
	 * 申请审核
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws Exception
	 */
	public String askCheck(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,Exception {
		Resource resource = doForm(request);
		resource.setStatus(CheckConstant.STATUS_WAIT_CHECK);
		if(iResource.askCheck(resource)){
			resString = "申请成功";
		}else{
			resString = "申请失败";
		}
		request.setAttribute("resString", resString);
		return list(request, response);
	}	
	/**
	 * 下载并审核
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws Exception
	 */
	public void downloadAndCheck(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,Exception {
		Resource resource = doForm(request);
		resource = iResource.getResourceById(resource.getResourceId());
		String root = request.getSession().getServletContext().getRealPath("/");
		String fileName = resource.getFileName();
		writeDownlaodFile(response, resource, root, fileName);
	}
	/**
	 * 写要下载的文件到本地硬盘
	 * @param response
	 * @param resource
	 * @param root
	 * @param fileName
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private void writeDownlaodFile(HttpServletResponse response,
			Resource resource, String root, String fileName)
			throws FileNotFoundException, IOException {
		// path是指欲下载的文件的路径。
        File file = new File(root + resource.getFilePath());
        System.out.println(root+":"+resource.getFilePath());
        if(file.exists()){
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setContentType("application/octet-stream;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        }
	}	
	
	/**
	 * 通过fileupload写文件到服务器上
	 * @param item
	 * @param relativePath upload/userId/resource/2014-7-25/uuid.jpg
	 * @param uploadDir upload/userId/resource/2014-7-25/file.jpg
	 * @param root D:/Tomcat 7.0/wtpwebapps/xiia/upload/userId/resource/2014-7-25/uuid.jpg
	 * @throws Exception
	 */
	private void uploadFileByItem(FileItem item,String relativePath,String uploadDir,String root) 
			throws Exception{
		String serverDirPath = root + uploadDir;
		File dir = new File(serverDirPath);
		if(!(dir.isDirectory() && dir.exists())){
			dir.mkdirs();
		}
		File file = new File(root+relativePath);
		item.write(file);
	}
	/**
	 * 判断上传的文件类型是否被支持
	 * @param ext 文件后缀
	 * @return 支持返回true，不支持返回false;
	 */
	private boolean isAcceptExtFile(String ext){
		String[] acceptExt = ParamUtil.ACCEPT_UPLOAD_RESOURCE_FILE_TYPE.split(",");
		boolean isAcceptExt = false;
		for(String a:acceptExt){
			if(ext.equals(a)){
				isAcceptExt = true;
			}
		}
		return isAcceptExt;
	}
	/**
	 * 从http请求中创建ResourceSort对象
	 * @param request
	 * @return 返回ResourceSort对象
	 * @throws Exception 
	 */
	private Resource doForm(HttpServletRequest request) 
			throws Exception{
		Resource resource = new Resource();
	
		if (request.getParameter("resourceId") != null){
			resource.setResourceId(Integer.parseInt(request.getParameter("resourceId")));
		}if (request.getParameter("sortId") != null){
			resource.setSortId(Integer.parseInt(request.getParameter("sortId")));
		}if (request.getParameter("userId") != null){
			resource.setUserId(Integer.parseInt(request.getParameter("userId")));	
		}if (request.getParameter("downloadCount") != null){
			resource.setDownloadCount(Integer.parseInt(request.getParameter("downloadCount")));
		}if (request.getParameter("resScore") != null){
			resource.setResScore(Integer.parseInt(request.getParameter("resScore")));
		}if (request.getParameter("status") != null){
			resource.setResScore(Integer.parseInt(request.getParameter("status")));
		}if (request.getParameter("fileName") != null){
			resource.setFileName(request.getParameter("fileName"));
		}if (request.getParameter("filePath") != null){
			resource.setFilePath(request.getParameter("filePath"));
		}if (request.getParameter("fileSize") != null){
			resource.setFileSize(Double.parseDouble(request.getParameter("fileSize")));
		}
		return resource;
	}
}
	

	
		
		

		


